import {CustomerClass, instantiateAllCustomers} from "@/Game/Customer";
import {AllEventList, EventClass} from "@/Game/Event";
import {instantiateAllShops, ShopClass} from "@/Game/Shop";
import {ShuffleArray, ShuffleArrayReturnNew, sleep} from "@/Game/CommonMethods";
import {defaultPlayerPurchaseOption, defaultPlayerServeOption, PlayerPurchaseType, PlayerServeOption} from "@/Game/Robot";
import {AllDishListDesc} from "@/Game/Dish";
import {Game, GameStage} from "@/Game/Game";
import {defaultClearShopGroundPrice} from "@/Game/PlayerArea";

const defaultDishCount = [16, 12, 12, 4];

export class CommonArea {
    game: Game;
    customerAndEventDrawPile: (CustomerClass | EventClass)[];
    customerAndEventDiscardPile: (CustomerClass | EventClass)[];
    customerQueue: CustomerClass[];
    customerQueueSize: number;
    customerQueueEnabled: boolean;
    persistentEvent: EventClass | null;
    lastEvent: EventClass | null;
    shopDrawPile: ShopClass[];
    shopQueue: ShopClass[];
    dishCount: number[];
    shopAndDishQueueEnabled: boolean;

    humanSelectingCustomer: boolean;
    selectedCustomerIndex: number;

    constructor(game: Game) {
        this.game = game;
        this.customerAndEventDrawPile = [];
        this.customerAndEventDiscardPile = [];
        this.customerQueue = [];
        this.shopDrawPile = [];
        this.shopQueue = [];
        this.dishCount = [0, 0, 0, 0];
        this.shopAndDishQueueEnabled = false;
    }

    startNewGame() {
        this.customerAndEventDrawPile = ShuffleArrayReturnNew([...instantiateAllCustomers(2), ...AllEventList]);
        this.customerAndEventDiscardPile = [];
        this.customerQueue = [];
        this.customerQueueSize = 4;
        this.customerQueueEnabled = false;
        this.persistentEvent = null;
        this.lastEvent = null;
        this.shopDrawPile = ShuffleArrayReturnNew(instantiateAllShops(3));
        this.shopQueue = [];
        this.dishCount = [...defaultDishCount];
        this.shopAndDishQueueEnabled = false;
        this.humanSelectingCustomer = false;
    }

    async beforePlayerOperation() {
        if (this.game.gameStage == GameStage.BeforePlayerOperation) {
            if (this.shopQueue.length < 4) {
                let unshiftCount = 4 - this.shopQueue.length;
                await sleep(50);
                this.shopQueue.unshift(...this.shopDrawPile.splice(this.shopDrawPile.length - unshiftCount, unshiftCount));
            }
            if (this.customerQueue.length < this.customerQueueSize) {
                if (this.customerAndEventDrawPile.length == 0) {
                    ShuffleArray(this.customerAndEventDiscardPile);
                    this.customerAndEventDrawPile = [...this.customerAndEventDiscardPile];
                    this.customerAndEventDiscardPile.length = 0;
                }
                let x = 0;
                while (this.customerQueue.length < this.customerQueueSize) {
                    if (x++ > 50) {
                        break;
                    }
                    let newCard = this.customerAndEventDrawPile.pop();
                    if (newCard instanceof CustomerClass) {
                        newCard.Fund = 0;
                        this.customerQueue.unshift(newCard);
                    }
                    else if (newCard instanceof EventClass) {
                        if (this.persistentEvent) {
                            if (this.persistentEvent.LoseEffect) {
                                this.persistentEvent.LoseEffect(this.game);
                            }
                            this.customerAndEventDiscardPile.push(this.persistentEvent);
                            this.persistentEvent = null;
                        }
                        this.lastEvent = newCard;
                        if (newCard.Persistent) {
                            this.persistentEvent = newCard;
                        }
                        else {
                            this.customerAndEventDiscardPile.push(newCard);
                        }
                        if (newCard.TakeEffect) {
                            newCard.TakeEffect(this.game);
                        }
                    }
                    await sleep(50);
                }
                if (this.customerQueue.length > this.customerQueueSize) {
                    this.customerAndEventDiscardPile.push(...this.customerQueue.splice(this.customerQueueSize));
                }
            }
            setTimeout(() => this.game.playerPurchase(), 1000);
        }
    }

    playerPurchase() {
        if (this.game.gameStage == GameStage.PlayerPurchase) {
            let playerArea = this.game.playerAreas[this.game.activePlayerIndex];
            if (playerArea.moneyOwned <= 0) {
                this.purchaseCompleted();
                return;
            }
            if (playerArea.playByHuman) {
                this.shopAndDishQueueEnabled = true;
                this.game.toast("请购买店铺或菜品", -1);
            }
            else {
                let result = playerArea.robot?.playerPurchase(this.game) ?? defaultPlayerPurchaseOption;
                switch (result.Type) {
                    case PlayerPurchaseType.Shop:
                        setTimeout(() => {
                            this.purchaseShop(result.Index);
                        }, 500);
                        break;
                    case PlayerPurchaseType.Dish:
                        setTimeout(() => {
                            this.purchaseDish(result.Index);
                        }, 500);
                        break;
                    case PlayerPurchaseType.None:
                        this.purchaseCompleted();
                        break;
                }
            }
        }
    }

    purchaseDish(index: number) {
        if (this.game.gameStage == GameStage.PlayerPurchase) {
            let dish = AllDishListDesc[index];
            if (this.dishCount[dish.Class] <= 0) {
                this.purchaseCompleted();
                return;
            }
            let playerArea = this.game.playerAreas[this.game.activePlayerIndex];
            if (dish.Price > playerArea.moneyOwned) {
                this.game.toast(`资金不足，玩家 ${this.game.activePlayerIndex} 当前资金：${playerArea.moneyOwned}`);
                if (!playerArea.playByHuman) {
                    this.purchaseCompleted();
                }
            }
            else {
                playerArea.moneyOwned -= dish.Price;
                this.dishCount[dish.Class]--;
                playerArea.addDishToDiscardPile(dish.Class);
                this.purchaseCompleted();
            }
        }
    }

    purchaseShop(index: number) {
        if (this.game.gameStage == GameStage.PlayerPurchase) {
            let playerArea = this.game.playerAreas[this.game.activePlayerIndex];
            if (playerArea.shopOwned.length >= 8) {
                this.game.toast(`玩家 ${this.game.activePlayerIndex + 1} 的店铺数量已达上限`);
                return;
            }
            let shop = this.shopQueue[index];
            let clearShopGroundPrice = defaultClearShopGroundPrice[playerArea.shopOwned.length];
            let price = shop.Price + clearShopGroundPrice;
            if (price > playerArea.moneyOwned) {
                this.game.toast(`资金不足，所需资金：${shop.Price} + ${clearShopGroundPrice} = ${price}，玩家 ${this.game.activePlayerIndex} 当前资金：${playerArea.moneyOwned}`);
                if (!playerArea.playByHuman) {
                    this.purchaseCompleted();
                }
            }
            else {
                this.shopQueue.splice(index, 1);
                playerArea.moneyOwned -= price;
                playerArea.addShop(shop);
                this.purchaseCompleted();
            }
        }
    }

    purchaseCompleted() {
        if (this.game.gameStage == GameStage.PlayerPurchase) {
            this.game.showToast = false;
            this.shopAndDishQueueEnabled = false;
            if (this.game.playerAreas[this.game.activePlayerIndex].playByHuman) {
                this.game.playerTrimDish();
            }
            else {
                setTimeout(() => {
                    this.game.playerTrimDish();
                }, 500);
            }
        }
    }

    playerServe() {
        if (this.game.gameStage == GameStage.PlayerServe) {
            let playerArea = this.game.playerAreas[this.game.activePlayerIndex];
            if (playerArea.playByHuman) {
                this.customerQueueEnabled = true;
                this.game.toast("请选择要招待的客人", -1);
            }
            else {
                let result: PlayerServeOption = playerArea.robot?.playerServe(this.game) ?? defaultPlayerServeOption;
                if (this.serveCustomer(result.CustomerIndex)) {
                    playerArea.selectShop(result.ShopIndex);
                }
            }
        }
    }

    serveCustomer(index: number): boolean {//返回结果用于表明是否需要选择商店
        if (this.game.gameStage == GameStage.PlayerServe) {
            let playerArea = this.game.playerAreas[this.game.activePlayerIndex];
            if (index < 0 || index >= this.customerQueue.length) {
                index = this.customerQueue.length - 1;
            }
            let customersCountInFront = this.customerQueue.length - index - 1;
            if (customersCountInFront > 0) {
                if (playerArea.moneyOwned >= customersCountInFront) {
                    if (playerArea.playByHuman) {
                        this.game.confirm("请确认", `招待该客人需要向前面的 ${customersCountInFront} 位客人各支付 1 两钱（下次选择仍然需要支付）`, () => {
                            this.game.showConfirmDialog = false;
                            playerArea.moneyOwned -= customersCountInFront;
                            for (let i = index + 1; i < this.customerQueue.length; i++) {
                                let customer = this.customerQueue[i];
                                customer.Fund++;
                            }
                            this.selectedCustomerIndex = index;
                            return playerArea.serveCustomer(this.customerQueue[index]);
                        });
                    }
                    else {
                        return playerArea.serveCustomer(this.customerQueue[this.customerQueue.length - 1]);
                    }
                }
                else {
                    this.game.toast(`资金不足，要招待该客人需要向前面的 ${customersCountInFront} 位客人各支付 1 两钱`);
                }
            }
            else {
                this.selectedCustomerIndex = index;
                return playerArea.serveCustomer(this.customerQueue[index]);
            }
        }
        return false;
    }
}